package it.polimi.meteocal.ejb.eventmanagement;


import it.polimi.meteocal.ejb.usermanagement.User;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class PacchettoBean
 */
@Stateless
public class EventMgrBean implements EventMgr {
	
	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;

	
	@Override
	public void save(EventDTO event) {
		Event newEvent = new Event(event);
		newEvent.setUser(em.find(User.class,context.getCallerPrincipal().getName()));
		em.persist(newEvent);
		System.out.println("Event saved >"+newEvent.getInsideOutside()+"<");
	}

	@Override
	public void delete(int eventid) {
		Event event = em.find(Event.class,eventid);
		//em.getTransaction().begin();
		em.remove(event);
		//em.getTransaction().commit();
	}

	@Override
	public void modify(EventDTO newEvent, int eventid) {
		Event event = em.find(Event.class, eventid);
		//em.getTransaction().begin();
		event.setBegin(newEvent.getBegin());
		event.setDescription(newEvent.getDescription());
		event.setEnd(newEvent.getEnd());
		event.setInsideOutside(newEvent.getInsideOutside());
		event.setName(newEvent.getName());
		event.setPlace(newEvent.getPlace());
		//em.getTransaction().commit();
		//em.refresh(event);
	}
	
	public User trova(String username){
		return em.find(User.class, username);
	}
	
	public User getPrincipalUser(){
		return trova(getPrincipalUsername());
	}
	
	public String getPrincipalUsername(){
		return context.getCallerPrincipal().getName();
	}

	
	@Override
	public List<?> findMyEvents(){
		Query q = em.createNamedQuery("Event.findByUser"); 
		q.setParameter("email", getPrincipalUser().getEmail());
		System.out.println("num: "+q.getResultList().size());
		return q.getResultList();		
	}
	
	@Override
	public List<?> myTomorrowEvents(){
		Query q = em.createNamedQuery("Event.myTomorrowEvents"); 
		q.setParameter("email", getPrincipalUser().getEmail());
		GregorianCalendar calendar = new GregorianCalendar();
		Date date = calendar.getTime();
		Timestamp ts_date = new Timestamp(date.getTime());
		q.setParameter("todayDate", ts_date);
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		date = calendar.getTime();
		ts_date = new Timestamp(date.getTime());
		q.setParameter("tomorrowDate", ts_date);
		System.out.println("num: "+q.getResultList().size());
		return q.getResultList();	
	}

}
